﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Dune.DAL.Managers
{
    public class EntityCodeManager
    {

        static readonly Dictionary<int, Type> codesTypes;
        static readonly Dictionary<Type, int> typesCodes;

        static EntityCodeManager()
        {
            codesTypes = new Dictionary<int, Type>(50);
//            codesTypes[101] = typeof(Order);
//            codesTypes[102] = typeof(OrderItem);
//            codesTypes[5] = typeof(Customer);
//            codesTypes[4] = typeof(CustomerGroup);
//            codesTypes[6] = typeof(Employee);
//            codesTypes[0] = typeof(TextEntity);
//            codesTypes[107] = typeof(SpecialBid);

            //Tasks range of ID = 200 ... 250. Homich
//            codesTypes[200] = typeof(TestTask);
//            codesTypes[201] = typeof(CustomerHoldTask);
//            codesTypes[202] = typeof(CreditCardPaymentTask);
//            codesTypes[203] = typeof(CustomerCreditLimitTask);
//            codesTypes[204] = typeof(ProductRequestTask);
//            codesTypes[205] = typeof(CustomerCreditLimitFOTask);
//            codesTypes[206] = typeof(CustomerCreditLimitAndHoldTask);
//            codesTypes[207] = typeof(TechcheckTask);
//
//            codesTypes[300] = typeof(Book);


            typesCodes = new Dictionary<Type, int>(codesTypes.Count);
            foreach (KeyValuePair<int, Type> pair in codesTypes)
            {
                typesCodes[pair.Value] = pair.Key;
            }

        }

        public int GetCode(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type");

            Type foundType = null;

            foreach (Type possibleType in typesCodes.Keys)
            {

                if (!possibleType.IsAssignableFrom(type))
                    continue;

                if (foundType == null)
                    foundType = possibleType;
                else if (foundType.IsAssignableFrom(possibleType))
                    foundType = possibleType;

            }
            if (foundType != null)
            {
                return typesCodes[foundType];
            }
            else
                throw new ArgumentException("ïnvalid type " + type);
        }



        public Type GetType(int code)
        {
            if (codesTypes.ContainsKey(code))
            {
                return codesTypes[code];
            }
            else
                throw new ArgumentException("ïnvalid code " + code);
        }

    }
}
